<?php

class My_Plugin_Acl extends Zend_Controller_Plugin_Abstract {

    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        $acl = new Zend_Acl;

        // dodajemy role
        $acl->addRole(new Zend_Acl_Role('guest'));
        $acl->addRole(new Zend_Acl_Role('user'));
        $acl->addRole(new Zend_Acl_Role('admin'));
        $acl->addRole(new Zend_Acl_Role('operator'));

        // dodajemy zasoby
        $acl->add(new Zend_Acl_Resource('index'));
        $acl->add(new Zend_Acl_Resource('error'));
        $acl->add(new Zend_Acl_Resource('kontakt'));
        $acl->add(new Zend_Acl_Resource('admin'));
        $acl->add(new Zend_Acl_Resource('login'));
        $acl->add(new Zend_Acl_Resource('register'));
        $acl->add(new Zend_Acl_Resource('raporty'));
        $acl->add(new Zend_Acl_Resource('uzytkownik'));

        // przydzielamy prawa
        $acl->allow('admin', null); // admin ma nieograniczone uprawnienia
        $acl->deny('admin', 'login', null);
        $acl->allow('admin', 'login', 'logout');
        $acl->allow('admin', 'login', 'finish');
        $acl->deny('admin', 'register', null);
        $acl->deny('admin', 'index', 'pacjenci');
        
        // przydzielamy prawa
        $acl->allow('operator', null); // admin ma nieograniczone uprawnienia
        $acl->deny('operator', 'login', null);
        $acl->allow('operator', 'login', 'logout');
        $acl->allow('operator', 'login', 'finish');
        $acl->deny('operator', 'register', null);
        
        $acl->allow('guest', 'error', null);
        $acl->allow('guest', 'kontakt', null);
        $acl->allow('guest', 'login', null);
        $acl->allow('guest', 'register', null);
        $acl->deny('guest', 'uzytkownik', null);
        $acl->deny('guest', 'admin', null);

        // rozpoczynamy sprawdzanie uprawnień
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $identity = $auth->getIdentity();
            $rola = $identity->rola;
        } else {
            $rola = 'guest';
        }
        $controller = $request->controller;
        $action = $request->action;
        if (!$acl->isAllowed($rola, $controller, $action)) {
            $request->setControllerName('login');
            $request->setActionName('index');
        }
    }

}